<template>
  <div class="search-suggestion">
    <van-cell
      @click="$emit('search', item)"
      v-for="(item, index) in list"
      :key="index"
      :title="item"
      icon="search"
    >
      <div slot="title" v-html="reverseStr(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSameSuggestion } from '@/api/han/search.js'
import lodash from 'lodash'
// lodash.debounce(function(){要做的事情},事件)===> 返回的是一个函数！
export default {
  name: 'searchSuggest',
  props: {
    searchText: {
      type: String,
    },
  },
  data() {
    return {
      list: [], // 搜索联想
    }
  },
  watch: {
    searchText: {
      // 监听函数
      //   async handler(){
      //   let res = await getSameSuggestion({
      //     keyword:this.searchText
      //   })
      //   this.list = res
      //   console.log(res);
      // },
      // deep:false, // 是否深监听
      // immediate:true // 是否开始就执行
      handler: lodash.debounce(function (value) {
        this.loadSearchSuggestion(value)
      }, 200),
      deep: false, // 是否深监听
      immediate: true, // 是否立刻侦听
    },
  },
  methods: {
    // 获取搜索建议
    async loadSearchSuggestion(val) {
      let res = await getSameSuggestion({
        keyword: val,
      })
      this.list = res.data.data
      console.log(res.data.data)
    },
    // 字符串高亮处理
    reverseStr(val) {
      try {
        return val.replaceAll(
          this.searchText,
          `<span style="color:red">${this.searchText}</span>`,
        )
      } catch (error) {
        return null
      }
    },
  },
}
</script>

<style></style>
